<template>
  <div class="base-container">
    <t-form ref="form" :data="queryParams" label-width="80" @submit="onSubmit">
      <t-row style="border-bottom: 1px solid #e5e6eb; margin-bottom: 10px">
        <t-col :span="11" class="query-form-inline">
          <t-form-item label="年份" name="year">
            <t-select style="width: 240px" v-model="queryParams.year" :options="years" placeholder="请选择表单年份" />
          </t-form-item>
          <t-form-item clearable label="待填表单" name="table">
            <t-select
              style="width: 240px"
              v-model.lazy="selectTable"
              :options="myTableOptions"
              placeholder="请选择表单"
            ></t-select>
          </t-form-item>
        </t-col>
        <t-col :span="1" class="operation-container">
          <!-- <t-button theme="primary" type="submit">查询</t-button> -->
          <!-- <t-button theme="default" variant="outline" type="reset">重置</t-button> -->
        </t-col>
      </t-row>
    </t-form>
    <div class="btn-group-inline">
      <t-button variant="outline" theme="primary" @click="addInfo">
        <t-icon name="add" slot="icon" />
        新增信息
      </t-button>
    </div>
    <t-table :loading="loading" rowKey="id" :data="tableData" :columns="tableColumns" :pagination="pagination" bordered>
      <!-- 单位基本信息 -->
      <template #institutional="{ row }">
        {{ row.institutional | filterByDict(dict.type.institutional) }}
      </template>
      <template #legalNature="{ row }">
        {{ row.legalNature | filterByDict(dict.type.legal_nature) }}
      </template>
      <template #hightechEnterprise="{ row }">
        <t-switch
          disabled
          size="large"
          :defaultValue="row.hightechEnterprise"
          :label="['是', '否']"
          :customValue="['1', '0']"
        ></t-switch>
      </template>
      <template #technologyEnterprise="{ row }">
        <t-switch
          disabled
          size="large"
          :defaultValue="row.technologyEnterprise"
          :label="['是', '否']"
          :customValue="['1', '0']"
        ></t-switch>
      </template>
      <template #approveStatus="{ row }">
        <t-switch
          disabled
          size="large"
          @change="postInfo(row)"
          v-model="row.approveStatus"
          :label="['提交', '暂存']"
          :customValue="['2', '1']"
        ></t-switch>
      </template>

      <!-- 科研条件 -->
      <!-- <template #researchConditionBase="{ row }">
        {{row}}
      </template> -->

      <!-- 操作按钮 -->
      <template #op="{ row }">
        <t-button @click="handleEdit(row)" size="small" variant="text" class="t-button-link">
          <t-icon name="edit-1" slot="icon" />
          修改
        </t-button>
        <t-button @click="handleDelete(row)" size="small" variant="text" class="t-button-link" theme="danger">
          <t-icon name="delete" slot="icon" />
          删除
        </t-button>
      </template>
    </t-table>
    <t-dialog :closeOnOverlayClick="false" theme="warning" header="提示" :visible.sync="dialog.open_delete_info" @confirm="deleteInfo">
      <div>确实删除该信息吗？</div>
    </t-dialog>
    <div v-if="queryParams.table === 'DWJBXX'">
      <tab-unit-base-info
        v-if="dialog.open_info_detail"
        :visible.sync="dialog.open_info_detail"
        :infoId="dialog.select_info_id"
        @reload="reloadTable"
      />
    </div>
    <div v-if="queryParams.table === 'RYGM'">
      <tab-personnel-size
        v-if="dialog.open_info_detail"
        :visible.sync="dialog.open_info_detail"
        :infoId="dialog.select_info_id"
        @reload="reloadTable"
      />
    </div>
    <div v-if="queryParams.table === 'KYTJ'">
      <tab-research-conditions
        v-if="dialog.open_info_detail"
        :visible.sync="dialog.open_info_detail"
        :infoId="dialog.select_info_id"
        @reload="reloadTable"
      />
    </div>
    <div v-if="queryParams.table === 'JTYSYJKFJFZC'">
      <tab-research-and-development-expenditure
        v-if="dialog.open_info_detail"
        :visible.sync="dialog.open_info_detail"
        :infoId="dialog.select_info_id"
        @reload="reloadTable"
      />
    </div>
    <div v-if="queryParams.table === 'JTYSKJXM'">
      <tab-technology-projec
        v-if="dialog.open_info_detail"
        :visible.sync="dialog.open_info_detail"
        :infoId="dialog.select_info_id"
        @reload="reloadTable"
      />
    </div>
    <div v-if="queryParams.table === 'JTYSKJCG'">
      <tab-technological-achievements
        v-if="dialog.open_info_detail"
        :visible.sync="dialog.open_info_detail"
        :infoId="dialog.select_info_id"
        @reload="reloadTable"
      />
    </div>
    <div v-if="queryParams.table === 'GJKJHZYJL'">
      <tab-cooperation-and-communication
        v-if="dialog.open_info_detail"
        :visible.sync="dialog.open_info_detail"
        :infoId="dialog.select_info_id"
        @reload="reloadTable"
      />
    </div>
    <div v-if="queryParams.table === 'JTHYZDSYS'">
      <tab-key-laboratory
        v-if="dialog.open_info_detail"
        :visible.sync="dialog.open_info_detail"
        :infoId="dialog.select_info_id"
        @reload="reloadTable"
      />
    </div>
    <div v-if="queryParams.table === 'BZHQK'">
      <tab-standardization
        v-if="dialog.open_info_detail"
        :visible.sync="dialog.open_info_detail"
        :infoId="dialog.select_info_id"
        @reload="reloadTable"
      />
    </div>
  </div>
</template>

<script>
import TabUnitBaseInfo, { tableColumns as tc1, tabKey as tk1 } from '../TabUnitBaseInfo/index.vue';
import TabPersonnelSize, { tableColumns as tc2, tabKey as tk2 } from '../TabPersonnelSize/index.vue';
import TabResearchConditions, { tableColumns as tc3, tabKey as tk3 } from '../TabResearchConditions/index.vue';
import TabResearchAndDevelopmentExpenditure from '../TabResearchAndDevelopmentExpenditure/index.vue';
import TabTechnologyProjec from '../TabTechnologyProjec/index.vue';
import TabTechnologicalAchievements from '../TabTechnologicalAchievements/index.vue';
import TabCooperationAndCommunication from '../TabCooperationAndCommunication/index.vue';
import TabKeyLaboratory from '../TabKeyLaboratory/index.vue';
import TabStandardization from '../TabStandardization/index.vue';
import { getDept } from '@/api/system/dept';

function genYears() {
  const curYear = new Date().getFullYear();
  const years = [];
  for (let i = 0; i < 5; i++) {
    const t = curYear - i;
    years.push({ label: t.toString(), value: t });
  }
  return years;
}

export default {
  name: 'process',
  components: {
    TabUnitBaseInfo,
    TabPersonnelSize,
    TabResearchConditions,
    TabResearchAndDevelopmentExpenditure,
    TabTechnologyProjec,
    TabTechnologicalAchievements,
    TabCooperationAndCommunication,
    TabKeyLaboratory,
    TabStandardization,
  },
  dicts: ['institutional', 'legal_nature'],
  data() {
    return {
      myTables: [],
      loading: true,
      years: genYears(),
      apiKey: '',
      tableData: [],
      tableColumns: [],
      pagination: {
        total: 0,
        showPageSize: false,
        showFirstAndLastPageBtn: false,
      },
      dialog: {
        open_info_detail: false,
        open_delete_info: false,
        select_info_id: -1,
      },
      queryParams: {
        year: new Date().getFullYear(),
        table: '',
        approveStatus: '1',
      },
    };
  },
  computed: {
    myTableOptions() {
      const { myTables } = this;
      return myTables.map((tab) => ({ label: tab.tableName, value: tab.tableCode }));
    },
    selectTable: {
      set(val) {
        this.queryParams.table = val;
        switch (val) {
        case 'DWJBXX':
          this.tableColumns = tc1;
          this.apiKey = tk1;
          break;
        case 'RYGM':
          this.tableColumns = tc2;
          this.apiKey = tk2;
          break;
        case 'KYTJ':
          this.tableColumns = tc3;
          this.apiKey = tk3;
          break;
        case 'JTYSYJKFJFZC':
          this.tableColumns = tc2;
          break;
        case 'JTYSKJXM':
          this.tableColumns = tc2;
          break;
        case 'JTYSKJCG':
          this.tableColumns = tc2;
          break;
        case 'GJKJHZYJL':
          this.tableColumns = tc2;
          break;
        case 'JTHYZDSYS':
          this.tableColumns = tc2;
          break;
        case 'BZHQK':
          this.tableColumns = tc2;
          break;
        default:
          break;
        }
        this.reloadTable();
      },
      get() {
        return this.queryParams.table;
      },
    },
  },
  created() {
    this.getMyTables();
  },
  methods: {
    onSubmit() {
      console.log('search table');
    },
    // 信息操作
    addInfo() {
      this.dialog.select_info_id = -1;
      this.dialog.open_info_detail = true;
    },
    handleEdit(row) {
      this.dialog.select_info_id = row.id;
      this.dialog.open_info_detail = true;
    },
    handleDelete(row) {
      this.dialog.select_info_id = row.id;
      this.dialog.open_delete_info = true;
    },
    async deleteInfo() {
      const { code } = await this.$api.kjtjdc.table[this.apiKey].del(this.dialog.select_info_id);
      if (code === 200) {
        this.reloadTable();
        this.$message.success('信息删除成功');
      }
      this.dialog.open_delete_info = false;
    },
    // 获取表数据
    async reloadTable() {
      this.loading = true;
      const { apiKey } = this;
      const { rows } = await this.$api.kjtjdc.table[apiKey].getMy(this.year);
      if (this.queryParams.table === 'DWJBXX') {
        const getUnitNamePromises = [];
        rows.forEach(row => {
          row.createTime = row.createTime.substr(0, 4);
          getUnitNamePromises.push(
            new Promise((resolve) => {
              getDept(row.name).then((res) => {
                row.name = res.data.deptName;
                resolve(row);
              });
            }),
          );
        })
        Promise.all(getUnitNamePromises).then((res) => {
          this.tableData = res;
          this.pagination.total = res.length;
          this.loading = false;
        });
      } else {
        this.tableData = rows;
        this.pagination.total = rows.length;
        this.loading = false;
      }
    },
    // 获取我的待填表单
    async getMyTables() {
      const { rows } = await this.$api.kjtjdc.table.getMyTables();
      this.myTables = rows;
      this.selectTable = rows[0].tableCode
    },
    // TODO: 仅修改审批状态
    postInfo(row) {
      console.log(row);
      // this.$api.kjtjdc.table.unitInfo.edit({ ...row }).then(res => {
      //   console.log(res)
      // })
      this.reloadTable();
    },
  },
};
</script>

<style lang="less" scoped></style>
